<template>
  <div class="document-list">
    <!-- 统计卡片区域 -->
    <div class="stat-cards">
      <el-card class="stat-card">
        <template #header>
          <div class="stat-header">
            <el-icon><Document /></el-icon>
            <span>总文档数</span>
          </div>
        </template>
        <div class="stat-value">{{ documents.length }}</div>
      </el-card>
      
      <el-card class="stat-card">
        <template #header>
          <div class="stat-header">
            <el-icon><Download /></el-icon>
            <span>总下载次数</span>
          </div>
        </template>
        <div class="stat-value">{{ totalDownloads }}</div>
      </el-card>
      
      <el-card class="stat-card">
        <template #header>
          <div class="stat-header">
            <el-icon><Files /></el-icon>
            <span>文件总大小</span>
          </div>
        </template>
        <div class="stat-value">{{ totalSize }}</div>
      </el-card>
    </div>

    <!-- 主要内容区域 -->
    <el-card class="main-card">
      <template #header>
        <div class="main-header">
          <div class="left-section">
            <h2 class="title">文档管理</h2>
            <el-input
              v-model="searchQuery"
              placeholder="搜索文档..."
              class="search-input"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <div class="right-section">
            <el-button type="danger" @click="handleDeleteSelected" :disabled="selectedDocuments.length === 0">
              <el-icon><Delete /></el-icon>删除选中 ({{ selectedDocuments.length }})
            </el-button>
            <el-button type="danger" @click="handleDeleteAll" :disabled="documents.length === 0">
              <el-icon><Delete /></el-icon>删除全部
            </el-button>
            <el-button type="primary" @click="handleUpload">
              <el-icon><Upload /></el-icon>上传文档
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="filteredDocuments" 
        style="width: 100%" 
        v-loading="loading"
        :header-cell-style="{ background: 'rgba(255, 255, 255, 0.05)' }"
        stripe
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column width="80" align="center" label="下载">
          <template #default="scope">
            <el-button link type="primary" @click="handleDownload(scope.row)" size="small">
              <el-icon><Download /></el-icon>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="文档名称" min-width="300">
          <template #default="{ row }">
            <div class="document-title">
              <el-icon :size="20" class="file-icon">
                <component :is="getFileIcon(row.file_type)" />
              </el-icon>
              <el-tooltip
                :content="row.title"
                placement="top"
                :show-after="500"
                :hide-after="2000"
              >
                <span class="title-text">{{ row.title }}</span>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="file_type" label="类型" width="100" align="center" />
        <el-table-column prop="file_size_formatted" label="大小" width="100" align="center" />
        <el-table-column prop="upload_time" label="上传时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.upload_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="download_count" label="下载次数" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getDownloadTagType(row.download_count)">
              {{ row.download_count }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template #default="scope">
            <el-button link type="danger" @click="handleDelete(scope.row)" size="small">
              <el-icon><Delete /></el-icon>删除
            </el-button>
            <el-button link type="primary" @click="handleDownload(scope.row)" size="small">
              <el-icon><Download /></el-icon>下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 批量操作工具栏 -->
      <div class="batch-actions" v-if="selectedDocuments.length > 0">
        <div class="batch-info">
          <el-icon><InfoFilled /></el-icon>
          <span>已选择 {{ selectedDocuments.length }} 个文档</span>
        </div>
        <div class="batch-buttons">
          <el-button size="small" @click="clearSelection">
            取消选择
          </el-button>
          <el-button type="primary" size="small" @click="handleBatchDownload" :disabled="selectedDocuments.length === 0">
            <el-icon><Download /></el-icon>批量下载
          </el-button>
          <el-button type="danger" size="small" @click="handleDeleteSelected" :disabled="selectedDocuments.length === 0">
            <el-icon><Delete /></el-icon>删除选中
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 上传对话框 -->
    <el-dialog v-model="uploadDialogVisible" title="上传文档" width="30%" center destroy-on-close>
      <el-upload
        class="upload-demo"
        drag
        :action="uploadUrl"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
        :data="uploadData"
        :headers="{
          'X-Requested-With': 'XMLHttpRequest',
          'Authorization': `Bearer ${localStorage.getItem('access_token')}`
        }"
        name="file"
        multiple
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽文件到此处或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持上传 DOC, DOCX, PDF, XLS, XLSX, PPT, PPTX 等格式文件
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '../utils/axios'  // 使用配置好的axios实例
import {
  Document,
  Files,
  Download,
  Upload,
  Search,
  Delete,
  Document as DocIcon,
  Grid as ExcelIcon,
  Picture as PptIcon,
  DocumentCopy as PdfIcon,
  More as OtherIcon,
  InfoFilled
} from '@element-plus/icons-vue'

const API_BASE_URL = `${import.meta.env.VITE_API_URL}/api`
const uploadUrl = `${API_BASE_URL}/documents/`

const documents = ref([])
const loading = ref(false)
const uploadDialogVisible = ref(false)
const uploadData = ref({})
const searchQuery = ref('')
const selectedDocuments = ref([])

// 计算属性
const filteredDocuments = computed(() => {
  if (!searchQuery.value) return documents.value
  const query = searchQuery.value.toLowerCase()
  return documents.value.filter(doc => 
    doc.title.toLowerCase().includes(query) ||
    doc.file_type.toLowerCase().includes(query)
  )
})

const totalDownloads = computed(() => {
  return documents.value.reduce((sum, doc) => sum + doc.download_count, 0)
})

const totalSize = computed(() => {
  const totalBytes = documents.value.reduce((sum, doc) => sum + doc.file_size, 0)
  return formatFileSize(totalBytes)
})

// 获取文档列表
const fetchDocuments = async () => {
  loading.value = true
  try {
    const response = await http.get('/documents/')
    
    // 处理响应数据 - 支持两种格式：直接数组或带分页的对象
    if (Array.isArray(response.data)) {
      documents.value = response.data
    } else if (response.data && response.data.results && Array.isArray(response.data.results)) {
      // 返回带分页信息的对象
      documents.value = response.data.results
    } else {
      // 如果返回的既不是数组也不是带results的对象，则设置为空数组
      console.warn('Unexpected response format:', response.data)
      documents.value = []
    }
    
    // 为每个文档添加格式化的文件大小
    documents.value.forEach(doc => {
      if (doc.file_size) {
        doc.file_size_formatted = formatFileSize(doc.file_size)
      } else {
        doc.file_size_formatted = '未知'
      }
    })
  } catch (error) {
    console.error('获取文档列表失败:', error)
    ElMessage.error('获取文档列表失败')
    documents.value = [] // 确保在错误情况下也设置为数组
  } finally {
    loading.value = false
  }
}

// 处理文件上传
const handleUpload = () => {
  uploadDialogVisible.value = true
}

// 处理上传成功
const handleUploadSuccess = (response) => {
  ElMessage.success('上传成功')
  uploadDialogVisible.value = false
  fetchDocuments()
}

// 处理上传失败
const handleUploadError = (error) => {
  console.error('上传失败:', error)
  ElMessage.error('上传失败：' + (error.message || '未知错误'))
}

// 处理文件删除
const handleDelete = async (file) => {
  try {
    await ElMessageBox.confirm('确定要删除这个文件吗？', '删除确认', {
      type: 'warning'
    })
    await http.delete(`/documents/${file.id}/`)
    ElMessage.success('删除成功')
    fetchDocuments()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 处理文件下载
const handleDownload = async (file) => {
  try {
    const response = await http.get(`/documents/${file.id}/download/`, {
      responseType: 'blob'
    })
    
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', file.title)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('下载成功')
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败')
  }
}

// 处理全部删除
const handleDeleteAll = async () => {
  try {
    // 第一次确认
    await ElMessageBox.confirm('确定要删除所有文档吗？此操作不可恢复！', '删除确认', {
      type: 'warning',
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      confirmButtonClass: 'el-button--danger'
    })
    
    // 二次确认，要求用户输入确认文本
    const { value: confirmText } = await ElMessageBox.prompt(
      '请输入"DELETE ALL"以确认删除所有文档',
      '二次确认',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        inputPattern: /^DELETE ALL$/,
        inputErrorMessage: '请输入正确的确认文本"DELETE ALL"',
        confirmButtonClass: 'el-button--danger',
        type: 'warning'
      }
    )
    
    if (confirmText !== 'DELETE ALL') {
      ElMessage.warning('操作已取消')
      return
    }
    
    loading.value = true
    
    // 创建一个删除所有文档的Promise数组
    const deletePromises = documents.value.map(doc => 
      http.delete(`/documents/${doc.id}/`)
    )
    
    // 并行执行所有删除请求
    await Promise.all(deletePromises)
    
    ElMessage.success('所有文档已删除')
    documents.value = [] // 清空本地文档列表
    selectedDocuments.value = [] // 清空选中列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 方法
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getFileIcon = (fileType) => {
  const type = fileType.toLowerCase()
  if (type === 'doc' || type === 'docx') return DocIcon
  if (type === 'xls' || type === 'xlsx') return ExcelIcon
  if (type === 'ppt' || type === 'pptx') return PptIcon
  if (type === 'pdf') return PdfIcon
  return OtherIcon
}

const getDownloadTagType = (count) => {
  if (count === 0) return 'info'
  if (count < 5) return ''
  if (count < 10) return 'success'
  return 'warning'
}

const handleSearch = () => {
  // 搜索逻辑已通过计算属性实现
}

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedDocuments.value = selection
}

// 处理删除选中文档
const handleDeleteSelected = async () => {
  if (selectedDocuments.value.length === 0) {
    ElMessage.warning('请先选择要删除的文档')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedDocuments.value.length} 个文档吗？此操作不可恢复！`, 
      '删除确认', 
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    loading.value = true
    
    // 创建一个删除选中文档的Promise数组
    const deletePromises = selectedDocuments.value.map(doc => 
      http.delete(`/documents/${doc.id}/`)
    )
    
    // 并行执行所有删除请求
    await Promise.all(deletePromises)
    
    ElMessage.success(`已删除 ${selectedDocuments.value.length} 个文档`)
    
    // 从本地列表中移除已删除的文档
    const deletedIds = selectedDocuments.value.map(doc => doc.id)
    documents.value = documents.value.filter(doc => !deletedIds.includes(doc.id))
    
    // 清空选中列表
    selectedDocuments.value = []
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 清除表格选择
const clearSelection = () => {
  selectedDocuments.value = []
  // 获取表格实例并清除选择
  const table = document.querySelector('.el-table__header-wrapper')
  if (table) {
    const checkbox = table.querySelector('.el-checkbox')
    if (checkbox) {
      checkbox.click()
    }
  }
}

// 批量下载文档
const handleBatchDownload = async () => {
  if (selectedDocuments.value.length === 0) {
    ElMessage.warning('请先选择要下载的文档')
    return
  }
  
  try {
    ElMessage.info(`开始下载 ${selectedDocuments.value.length} 个文档，请稍候...`)
    
    // 逐个下载文档，避免浏览器阻止多个下载
    for (const doc of selectedDocuments.value) {
      await handleDownload(doc)
      // 添加短暂延迟，避免浏览器阻止连续下载
      await new Promise(resolve => setTimeout(resolve, 500))
    }
    
    ElMessage.success(`已下载 ${selectedDocuments.value.length} 个文档`)
  } catch (error) {
    console.error('批量下载失败:', error)
    ElMessage.error('批量下载失败，请稍后重试')
  }
}

// 在组件挂载时获取文档列表
onMounted(() => {
  fetchDocuments()
})
</script>

<style scoped>
.document-list {
  padding: 20px;
  min-height: 100vh;
  color: var(--el-text-color-primary);
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.stat-header {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--el-color-primary);
  text-align: center;
  margin-top: 10px;
}

.main-card {
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.main-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.main-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.title {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.search-input {
  width: 300px;
}

.document-title {
  display: flex;
  align-items: center;
  gap: 8px;
  max-width: 100%;
  
  .file-icon {
    flex-shrink: 0;
    color: #909399;
  }

  .title-text {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    color: #303133;
    font-size: 14px;
    transition: color 0.3s ease;

    &:hover {
      color: var(--el-color-primary);
    }
  }
}

.el-table {
  border-radius: 4px;
  overflow: hidden;
}

/* 上传对话框样式 */
.upload-demo {
  display: flex;
  justify-content: center;
}

.el-upload {
  width: 100%;
}

.el-upload-dragger {
  width: 100%;
  height: 200px;
}

.el-upload__tip {
  text-align: center;
  margin-top: 10px;
  color: #909399;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .stat-cards {
    grid-template-columns: 1fr;
  }
  
  .main-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .left-section {
    flex-direction: column;
    width: 100%;
  }
  
  .search-input {
    width: 100%;
  }
}

/* 表格样式适配深色主题 */
:deep(.el-table) {
  background-color: transparent !important;
  --el-table-border-color: rgba(255, 255, 255, 0.1);
  --el-table-header-bg-color: rgba(255, 255, 255, 0.05);
  --el-table-tr-bg-color: transparent;
  --el-table-row-hover-bg-color: rgba(255, 255, 255, 0.08);
}

:deep(.el-table th) {
  background-color: rgba(255, 255, 255, 0.05) !important;
  color: var(--el-text-color-primary);
}

:deep(.el-table td) {
  background-color: transparent;
  border-bottom-color: rgba(255, 255, 255, 0.1);
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: rgba(255, 255, 255, 0.02);
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  background-color: rgba(255, 255, 255, 0.08);
  transform: none;
}

/* 防止卡片和表格行在悬停时有任何水平方向的移动 */
:deep(.el-card),
:deep(.el-table__row) {
  transform-origin: center;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

:deep(.el-table__row:hover) {
  transform: none;
}

/* 按钮样式增强 */
:deep(.el-button--text) {
  color: var(--el-color-primary);
  font-weight: 500;
}

:deep(.el-button--text.el-button--danger) {
  color: #EF4444;
}

:deep(.el-button--text.el-button--success) {
  color: #10B981;
}

:deep(.el-button--text.el-button--warning) {
  color: #F59E0B;
}

:deep(.el-button--text.el-button--info) {
  color: #6B7280;
}

/* 按钮悬停效果 - 只在垂直方向有变化 */
.el-button {
  transition: transform 0.3s ease, opacity 0.3s ease, background-color 0.3s ease !important;
}

.el-button:not(.is-link):hover {
  transform: translateY(-2px);
}

/* 链接按钮样式 */
:deep(.el-button.is-link) {
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

:deep(.el-button.is-link:hover) {
  background-color: rgba(255, 255, 255, 0.1);
  transform: none;
}

/* 批量操作工具栏样式 */
.batch-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.batch-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.batch-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style> 